package org.luxor.commons.mvc.wrapper;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


public class HttpRequestWrapper extends HttpServletRequestWrapper {

    private byte[] buffer;

    public HttpRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        ServletInputStream is = request.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) > 0) {
            os.write(b, 0, len);
        }
        this.buffer = os.toByteArray();
    }

    @Override
    public ServletInputStream getInputStream() {
        return new ExtendInputStream(this.buffer);
    }

    public byte[] getContext() {
        return this.buffer;
    }

    public void setContext(byte[] context) {
        this.buffer = context;
    }

    @Override
    public String toString() {
        return new String(this.buffer);
    }
}